<template>
  <a-modal title="完成换车" :visible="visible" width="85vw" unmount-on-close @cancel="close">
    <div class="page-container give-car-wrapper" style="position: relative">
      <page-form :model="form" :rules="rules" ref="formRef" layout="vertical">
        <card title="换下车信息" style="margin-top: 20px">
          <box-info :carId="form.replacedCarId" style="margin-bottom: 20px" />
          <page-form-row>
            <page-form-item label="出库里程" size="1/3"> {{ form.outCarMileage || 0 }}公里 </page-form-item>
            <page-form-item label="出库油(电)量" size="2/3"> {{ form.outCarOil || 0 }}</page-form-item>
          </page-form-row>
          <page-form-row>
            <page-form-item label="换下车里程" field="returnCarMileage">
              <i-input-number :precision="0" unit="公里" v-model="form.returnCarMileage" />
            </page-form-item>
            <page-form-item label="换下车油(电)量" field="returnFuelNum">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.returnFuelNum" />
            </page-form-item>
            <page-form-item field="replaceStaffId" label="换车人">
              {{ form.replaceStaffName || '-' }}
            </page-form-item>
            <page-form-item field="replaceTime" label="换车时间">
              <i-date-picker
                class="w-full"
                v-model="form.replaceTime"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:00"
                :disabled-date="disabledDate"
                :disabled-time="disabledTime"
                :time-picker-props="{
                  format: 'HH:mm',
                  defaultValue: '00:00',
                }"
                showTime
                popup-container=".give-car-wrapper"
              />
            </page-form-item>
            <page-form-item label="换下车照片" size="1">
              <upload-img v-model="form.returnFileIds" />
            </page-form-item>
            <page-form-item label="换下车视频" size="1" class="mb-0">
              <upload-video v-model="form.returnVideoFileIds" :max="1" />
            </page-form-item>
          </page-form-row>
        </card>

        <card title="换上车信息" :showDivider="false" style="margin-top: 20px">
          <box-info :carId="form.carId" style="margin-bottom: 20px" />
          <page-form-row>
            <page-form-item label="车辆来源">
              {{ form.carSource == 1 ? '门店车辆' : '跨门店调车' }}
            </page-form-item>
            <page-form-item field="carLicenseNo" label="车牌号">
              {{ form.carLicenseNo || '-' }}
            </page-form-item>
            <page-form-item label="排车车型" size="1"> {{ form.carModelName || '-' }} </page-form-item>
            <page-form-item label="换上车里程" size="1/3" field="giveCarMileage">
              <i-input-number :precision="0" unit="公里" v-model="form.giveCarMileage" />
            </page-form-item>
            <page-form-item label="换上车油(电)量" size="1/3" field="giveFuelNum">
              <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.giveFuelNum" />
            </page-form-item>
            <page-form-item label="换上车照片" size="1">
              <upload-img v-model="form.giveFileIds" />
            </page-form-item>
            <page-form-item label="换上车视频" size="1">
              <upload-video v-model="form.giveVideoFileIds" :max="1" />
            </page-form-item>
            <page-form-item label="换车备注" size="2/3">
              <i-textarea v-model="form.replaceRemark" />
            </page-form-item>
          </page-form-row>
        </card>
      </page-form>
      <!-- 订单费用信息 -->
      <div class="relative fee-pane-content">
        <page-form :model="feeForm" layout="vertical">
          <card title="换车费用" :showDivider="false">
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane :orderFeeIndex="index" :disabledOnlineFee="orderInfo.orderSource == 1" />
            </template>
          </card>
        </page-form>
      </div>
    </div>
    <template #footer>
      <a-button @click="close">关闭</a-button>
      <a-button type="primary" @click="submitFn" :loading="okLoading">确认</a-button>
    </template>
  </a-modal>
  <!-- 查询当前订单的换下车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>

<script setup name="LongOrderChangeCar">
  import { Message } from '@arco-design/web-vue'
  import { finishReplaceCar } from '@/api/business/workorder'
  import { ref, provide, computed, inject } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { Notification } from '@arco-design/web-vue'
  import feePane from '../giveCar/order-fee/fee-pane.vue'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import summaryInfo from '../giveCar/summary-info.vue'
  import boxInfo from '../../../components/box-modal.vue'
  import dayjs from 'dayjs'
  // import steps from './components/steps.vue'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  import carSelector from '@/views/assets/car/stock/car-selector.vue'
  import { getLongOrderDetails, replaceCar } from '@/api/order/czsOrder'
  import { checkExistEtcOrderApi } from '@/api/order/etcOrder'
  import finishEtcOrderModal from '@/views/order/etc-order/components/finish-etc-order-modal.vue'
  import { getStoreTemplateDetail, initFeeDetail, buildCostInfoParam } from '../giveCar/order-fee/fee-utils.js'
  import { handleContracList } from '../giveCar/utils'
  const emit = defineEmits(['ok'])
  const { navigateBack, navigateClose } = useNavigate()
  const dict = usePageDict('longOrderDict')
  const route = useRoute()
  const router = useRouter()
  const orderId = ref()
  const userStore = useUserStore()
  console.log('userStore', userStore)
  const orderInfo = ref({})
  const scrollbarRef = inject('scrollbarRef')
  const visible = ref(false)
  const orderType = ref(null)
  const expectEndTime = ref(null) // 换车时间

  const formRef = ref()

  // 滚动到顶部
  const scrollTopFn = () => {
    scrollbarRef && scrollbarRef.value.scrollTop(0)
  }
  // 步骤信息
  const stepList = ref([
    { stepText: '换车信息', stepNum: 1, active: true },
    { stepText: '费用信息', stepNum: 2, active: false },
  ])
  // rules
  const rules = ref({
    returnCarMileage: [{ required: true, message: '请输入换下车里程' }], // 换下车里程
    returnFuelNum: [{ required: true, message: '请输入换下车油(电)量' }], // 换下车油(电)量
    giveCarMileage: [{ required: true, message: '请输入换上车里程' }], // 换上车里程
    giveFuelNum: [{ required: true, message: '请输入换上车油(电)量' }], // 换上车油(电)量
    replaceStaffId: [{ required: true, message: '请选择换车人' }],
    replaceTime: [{ required: true, message: '请选择换车时间' }],
    licenseNo: { required: true, message: '请选择车牌号' },
  })

  // 默认员工
  const defaultStaffId = ref(userStore.employeeId)
  const form = ref({
    id: orderId.value,
    replaceTime: dayjs(expectEndTime.value).format('YYYY-MM-DD HH:mm:ss'),
    carSource: 1,
    replaceStaffId: defaultStaffId.value,
    contractList: [
      {
        contractFileId: '',
        contractNo: '',
        contractType: 2,
        contractTypeName: '换车合同',
        contractName: '',
        status: 'edit',
      },
    ],
    carLicenseNo: '',
  })
  const initForm = () => {
    form.value = {
      id: orderId.value,
      replaceTime: dayjs(expectEndTime.value).format('YYYY-MM-DD HH:mm:ss'),
      carSource: 1,
      replaceStaffId: defaultStaffId.value,
      contractList: [
        {
          contractFileId: '',
          contractNo: '',
          contractType: 2,
          contractTypeName: '换车合同',
          contractName: '',
          status: 'edit',
        },
      ],
      carLicenseNo: '',
    }
  }
  const changeContractList = ref([])
  const open = (record) => {
    console.log('record', record)
    expectEndTime.value = record.expectEndTime
    // 重置form
    initForm()
    // 负责人
    form.value.replaceStaffId = record.workOperatorId //工单负责人id
    form.value.replaceStaffName = record.workOperatorName // 工单负责人name
    // 车辆(换上)
    form.value.carSource = record.carSource
    form.value.carId = record.carId
    // 车辆(换下)
    form.value.replacedCarId = record.replacedCarId
    form.value.carLicenseNo = record.carLicenseNo
    form.value.carModelId = record.carModelId
    form.value.carModelName = record.carModelName

    visible.value = true
    form.value.id = record.id
    orderId.value = record.refId

    orderType.value = 2
    // 读取订单信息
    getLongOrderDetails({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      form.value.orderCarId = orderInfo.value.useOrderCarId
      // form.value.carId = orderInfo.value.carId
      form.value.siteId = orderInfo.value.siteId
      form.value.siteName = orderInfo.value.siteName
      form.value.originalModelId = orderInfo.value.originalModelId
      form.value.originalModelName = orderInfo.value.originalModelName
      form.value.expectedUseCarTime = orderInfo.value.expectedUseCarTime
      form.value.expectedReturnCarTime = orderInfo.value.expectedReturnCarTime
      form.value.leaseNumberStr = orderInfo.value.leaseNumberStr
      form.value.orderSourceName = orderInfo.value.orderSourceName
      // 出库里程、出库油电量取值修改
      if (Array.isArray(orderInfo.value.longOrderCarInfoDtos)) {
        let carInfoDtos = orderInfo.value.longOrderCarInfoDtos.slice(-1)[0]
        form.value.outCarMileage = carInfoDtos ? carInfoDtos.giveCarMileage : 0 // 出库里程
        form.value.outCarOil = carInfoDtos ? carInfoDtos.giveFuelAmount : 0 // 出库油电量
      }
      orderInfo.value.startTime = orderInfo.value.expectedUseCarTime
      orderInfo.value.endTime = orderInfo.value.expectedReturnCarTime
      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        // 更新费用模板 id
        priceTemplateId.value = templateId
        let feeValue = feeForm.value
        // 初始化费用
        initFeeDetail(feeValue, storeTemplate)
      })
      // 合同信息处理
      let orderContractList = orderInfo.value.contractList
      if (orderContractList && orderContractList.length > 0) {
        changeContractList.value = orderContractList.filter((item) => item.contractTypeName.indexOf('换车') !== -1)
        if (changeContractList.value.length == 0 || changeContractList.value.every((item) => item.contractFileId)) {
          changeContractList.value.push({
            contractFileId: '',
            contractNo: '',
            contractType: 2,
            contractTypeName: `换车合同${changeContractList.value.length + 1}`,
            contractName: '',
            status: 'edit',
          })
        }
      }
      form.value.contractList = handleContracList(changeContractList.value)
    })
  }
  // 关闭
  const close = () => {
    feeForm.value = {
      randomKey: 0,
      orderFee: [
        {
          // 费用类型（线上费用|线下费用）
          feeType: 1,
          feeDetailList: [],
          priceTemplateId: priceTemplateId,
          feeDetailTypeList: ['extraFee'],
        },
      ],
    }
    visible.value = false
  }
  // 保存
  const handleBeforeOk = () => {
    close()
    emit('ok')
  }
  defineExpose({
    open,
  })
  // 选择车牌
  const carSelectorRef = ref()
  const selectCarFn = () => {
    let startTime = orderInfo.value.startTime
    let endTime = orderInfo.value.endTime
    let replaceTime = form.value.replaceTime
    if (dayjs(replaceTime).valueOf() > dayjs(endTime).valueOf()) {
    } else {
      startTime = replaceTime
    }
    const param = {
      // siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      dateRange: [startTime, endTime],
      id: form.value.carId,
      ...platoonModelQueryParam.value,
      carSource: form.value.carSource,
    }
    carSelectorRef.value.open(
      param,
      {
        ...orderInfo.value,
        modelId: orderInfo.value.originalModelId,
        platoonCarId: orderInfo.value.carId,
      },
      'long-order'
    )
  }
  const lastGiveCarTime = computed(() => {
    const orderCarInfos = orderInfo.value.longOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return lastOrderCarInfo.useStartTime
  })
  // disabled Date|Time
  const disabledDate = (dateVal) => {
    const prevDate = lastGiveCarTime.value
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledTime = (current) => {
    let options = {}
    let prevDate = lastGiveCarTime.value
    if (prevDate) {
      let currentTime = current ? dayjs(current) : dayjs()
      let currentTime_year = currentTime.year()
      let currentTime_month = currentTime.month()
      let currentTime_date = currentTime.date()
      let currentTime_hour = currentTime.hour()
      let prevDateTime = dayjs(prevDate)
      let prevDateTime_year = prevDateTime.year()
      let prevDateTime_month = prevDateTime.month()
      let prevDateTime_date = prevDateTime.date()
      let prevDateTime_hour = prevDateTime.hour()
      let prevDateTime_minute = prevDateTime.minute()
      if (prevDateTime_minute == 59) {
        options.disabledHours = () => range(0, prevDateTime_hour + 1)
        options.disabledMinutes = () => []
      } else {
        options.disabledHours = () => range(0, prevDateTime_hour)
        options.disabledMinutes = () => range(0, prevDateTime_minute + 1)
      }
      // 用户选择的是 未来 的天
      if (currentTime_year > prevDateTime_year || currentTime_month > prevDateTime_month || currentTime_date > prevDateTime_date) {
        options = {}
      } else {
        // 用户选择的是 未来 的小时
        if (currentTime_hour > prevDateTime_hour) {
          options.disabledMinutes = () => {
            return []
          }
        }
      }
    }
    return options
  }
  // 统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.startTime ? `${orderInfoVal.startTime} - ${orderInfoVal.endTime}` : '-',
        },
        { label: '租期', value: orderInfoVal.leaseNumberStr },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '预订车型', value: orderInfoVal.originalSiteModelName },
        { label: '交车车型', value: orderInfoVal.modelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.licenseNo }],
    ]
  })
  // 选择车牌完成后
  // 记录弹窗queryParam
  const platoonModelQueryParam = ref({})
  const carConfirmFn = (id, option = {}, queryParam) => {
    form.value.carId = id
    form.value.licenseNo = option.licenseNo
    form.value.carModelId = option.modelId
    form.value.carModelName = option.modelName

    // 记录弹窗queryParam
    platoonModelQueryParam.value = { ...queryParam }
  }

  // 切换订单来源
  const changeCarSourceFn = () => {
    form.value.carId = undefined
    form.value.licenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
    platoonModelQueryParam.value = {}
  }

  provide('form', form)
  provide('dict', dict)

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 确认事件
  const okLoading = ref(false)
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    form.value.carLicenseNo = form.value.licenseNo
    let param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    let contractList = form.value.contractList
    param.contractFileId = contractList[0].fileId
    param.contractNo = contractList[0].contractNo
    param.contractName = contractList[0].contractName
    okLoading.value = true
    finishReplaceCar(param)
      .then((res) => {
        console.log(res)
        Message.success(res.result?.msg || res.message || '操作成功')
        close()
        emit('ok')
      })
      .finally(() => (okLoading.value = false))
  }
  // 检验换车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    formRef.value.validate((error) => {
      if (!error) {
        let params = {
          refType: 2,
          refId: orderId.value,
          carId: orderInfo.value.carId,
          endTime: form.value.replaceTime,
        }
        checkExistEtcOrderApi(params).then((res) => {
          let result = res.result
          if (result.existOrder) {
            let params = {
              carLicenseNo: orderInfo.value.licenseNo,
              operateStr: '换车',
            }
            etcModalRef.value.open(params)
          } else {
            submitOperateFn()
          }
        })
      }
    })
  }
</script>

<style lang="less" scoped>
  .contContainer {
    margin-top: 25px;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }
  .page-container {
    max-height: calc(100vh - 210px);
  }
</style>
